﻿using System.Reflection;
using Abp.Application.Services;
using Abp.Configuration.Startup;
using Abp.Modules;
using Abp.WebApi;
using Swashbuckle.Application;
using System.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Http;
using System.Web.Http.Cors;

namespace AVIS.OutBound
{
    [DependsOn(typeof(AbpWebApiModule), typeof(OutBoundApplicationModule))]
    public class OutBoundWebApiModule : AbpModule
    {
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

            Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
                .ForAll<IApplicationService>(typeof(OutBoundApplicationModule).Assembly, "avis")
                .Build();

            // 配置跨域
            GlobalConfiguration.Configuration.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            // 配置输出json时不使用骆驼式命名法，按对象属性原名输出
            //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
            //    new Newtonsoft.Json.Serialization.DefaultContractResolver();

            // 集成Swagger UI
            ConfigureSwaggerUi();
        }

        private void ConfigureSwaggerUi()
        {
            Configuration.Modules.AbpWebApi().HttpConfiguration
                .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "AVIS.OutBound.WebApi");
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

                    //将注释的XML文档添加到SwaggerUI中
                    ConfigXmlCommentsPath(c);
                })
                .EnableSwaggerUi(c =>
                {
                    //c.InjectJavaScript(Assembly.GetAssembly(typeof(OutBoundWebApiModule)), "AVIS.OutBound.WebApi.Scripts.Swagger-Custom.js");
                });
        }

        private void ConfigXmlCommentsPath(SwaggerDocsConfig config)
        {
            var modules = AbpModule.FindDependedModuleTypesRecursivelyIncludingGivenModule(typeof(OutBoundWebApiModule));
            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            foreach (var module in modules)
            {
                var commentsFileName = module.Assembly.GetName().Name + ".XML";
                var commentsFile = Path.Combine(baseDirectory, "bin", commentsFileName);
                if (File.Exists(commentsFile))
                {
                    config.IncludeXmlComments(commentsFile);
                }
            }
        }

    }
}
